package com.ruoyi.project.module.groupProperty.service;

import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.module.applicationProperty.domain.ApplicationProperty;
import com.ruoyi.project.module.applicationProperty.service.ApplicationPropertyServiceImpl;
import com.ruoyi.project.module.group.domain.Group;
import com.ruoyi.project.module.group.mapper.GroupMapper;
import com.ruoyi.project.module.remark.domain.Remark;
import com.ruoyi.project.module.remark.service.IRemarkService;
import com.ruoyi.project.module.task.mapper.TaskUtilsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.module.groupProperty.mapper.GroupPropertyMapper;
import com.ruoyi.project.module.groupProperty.domain.GroupProperty;
import com.ruoyi.project.module.groupProperty.service.IGroupPropertyService;
import com.ruoyi.common.support.Convert;

import javax.annotation.Resource;

/**
 * 配置组属性 服务层实现
 * <br>
 * com.ruoyi.project.module.groupProperty.service.GroupPropertyServiceImpl
 * <br>
 *
 * @author shoukaiseki
 * ブログ http://www.shoukaiseki.top/<br>
 * E-メール jiang28555@Gmail.com<br>
 * @date 2019-01-14 13:32:41<br>
 */
@Service
public class GroupPropertyServiceImpl implements IGroupPropertyService 
{

	static final Logger logger= LoggerFactory.getLogger(GroupPropertyServiceImpl.class);

	@Resource
	TaskUtilsMapper taskUtilsMapper;

	@Resource
	private GroupPropertyMapper groupPropertyMapper;

	@Resource
	private GroupMapper groupMapper;

	@Resource
	IRemarkService remarkService;

	/**
     * 查询配置组属性信息
     * 
     * @param configGroupPropertyId 配置组属性ID
     * @return 配置组属性信息
     */
    @Override
	public GroupProperty selectGroupPropertyById(Long configGroupPropertyId)
	{
	    return groupPropertyMapper.selectGroupPropertyById(configGroupPropertyId);
	}

	@Override
	public List<GroupProperty> lookupGroupPropertyList(GroupProperty groupProperty) {
		return groupPropertyMapper.lookupGroupPropertyList(groupProperty);
	}

	/**
     * 查询配置组属性列表
     * 
     * @param groupProperty 配置组属性信息
     * @return 配置组属性集合
     */
	@Override
	public List<GroupProperty> selectGroupPropertyList(GroupProperty groupProperty)
	{
	    return groupPropertyMapper.selectGroupPropertyList(groupProperty);
	}
	
    /**
     * 新增配置组属性
     * 
     * @param groupProperty 配置组属性信息
     * @return 结果
     */
	@Override
	public int insertGroupProperty(GroupProperty groupProperty)
	{
		Date currentDate = taskUtilsMapper.getCurrentDate();
		String userName = ShiroUtils.getUser().getLoginName();
		groupProperty.setCreateBy(userName);
		groupProperty.setCreateTime(currentDate);
		groupProperty.setUpdateBy(userName);
		groupProperty.setUpdateTime(currentDate);
		GroupProperty parentProject = groupPropertyMapper.selectGroupPropertyById(groupProperty.getParentId());



		if(parentProject!=null){
			groupProperty.setAncestors(parentProject.getAncestors() + "," + groupProperty.getParentId());
		}else {
			groupProperty.setAncestors("0");
		}
		groupMapper.updateModify(groupProperty.getConfigGroupId(),true);
	    return groupPropertyMapper.insertGroupProperty(groupProperty);
	}


	/**
     * 修改配置组属性
     * 
     * @param groupProperty 配置组属性信息
     * @return 结果
     */
	@Override
	public int updateGroupProperty(GroupProperty groupProperty)
	{
		Date currentDate = taskUtilsMapper.getCurrentDate();
		String userName = ShiroUtils.getUser().getLoginName();
		groupProperty.setCreateBy(null);
		groupProperty.setCreateTime(null);
		groupProperty.setUpdateBy(userName);
		groupProperty.setUpdateTime(currentDate);
		GroupProperty parentProject = groupPropertyMapper.selectGroupPropertyById(groupProperty.getParentId());


		if(parentProject!=null){
			groupProperty.setAncestors(parentProject.getAncestors() + "," + groupProperty.getParentId());
		}else {
			groupProperty.setAncestors("0");
		}

		//获取组id并设置
		GroupProperty temp = selectGroupPropertyById(groupProperty.getConfigGroupPropertyId());
		groupMapper.updateModify(temp.getConfigGroupId(),true);
	    return groupPropertyMapper.updateGroupProperty(groupProperty);
	}



	/**
     * 删除配置组属性对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteGroupPropertyByIds(Long configGroupId,String ids)
	{
		groupMapper.updateModify(configGroupId,true);
		List<Long>idList= Lists.newArrayList();
		for (String parentId:ids.split(",")) {
			idList.add(Long.parseLong(parentId));
			List<Long> chindsIdList = getChindsIdList(Long.parseLong(parentId));
			idList.addAll(chindsIdList);
		}



		List<String> idStrList = Lists.newArrayList();

		for (Long aLong : idList) {
			idStrList.add(String.valueOf(aLong));
		}
		logger.debug("idList={}",idList);
		if(logger.isDebugEnabled()){
		    //此处不能用,变参形式,因为结果是数组结构
			logger.debug("idList="+idStrList.toArray(new String[idStrList.size()]));
			//或者这样也可以
			logger.debug("idList={}",idStrList.toArray(new String[idStrList.size()]).toString());
		}
		return groupPropertyMapper.deleteGroupPropertyByIds(idStrList.toArray(new String[idStrList.size()]));
	}

	@Override
	public int maxOrderNum(Long configGroupId, Long parentId) {
		return groupPropertyMapper.maxOrderNum(configGroupId,parentId);
	}


	public List<Long> getChindsIdList(Long parentId){
		List<Long> list = Lists.newArrayList();
		List<GroupProperty> groupProperties = groupPropertyMapper.selectGroupPropertyListByParentId(parentId);
		for (GroupProperty groupProperty : groupProperties) {
			Long configGroupId = groupProperty.getConfigGroupPropertyId();
			list.add(configGroupId);
			List<Long> chindsList = getChindsIdList(configGroupId);
			list.addAll(chindsList);
		}
		return list;
	}


	@Override
	public boolean hasChilds(Integer parentId) {
		int childSize=groupPropertyMapper.childSize(parentId);
		return childSize==0?false:true;
	}

	@Override
	public void copy(Long sourceConfigGroupId, Long sourceParentId, Long targetConfigGroupId, Long targetParentId){
		String userName = ShiroUtils.getUser().getLoginName();
		List<GroupProperty> groupPropertyList = groupPropertyMapper.selectGroupPropertyListByConfigGroupIdAndParentId(sourceConfigGroupId, sourceParentId);
		for (GroupProperty groupPropertyTemp : groupPropertyList) {
		    GroupProperty groupProperty=new GroupProperty();
			BeanUtils.copyProperties(groupPropertyTemp,groupProperty);
			groupProperty.setConfigGroupId(targetConfigGroupId);
			groupProperty.setConfigGroupPropertyId(null);
			groupProperty.setCreateBy(userName);
			groupProperty.setCreateTime(new Date());
			groupProperty.setUpdateBy(userName);
			groupProperty.setUpdateTime(new Date());
			groupProperty.setParentId(targetParentId);
			GroupProperty parentProject = groupPropertyMapper.selectGroupPropertyById(targetParentId);
			if(parentProject!=null){
				groupProperty.setAncestors(parentProject.getAncestors() + "," + targetParentId);
			}else {
				groupProperty.setAncestors("0");
			}
			groupPropertyMapper.insertGroupProperty(groupProperty);
			copy(sourceConfigGroupId,groupPropertyTemp.getConfigGroupPropertyId(),targetConfigGroupId,groupProperty.getConfigGroupPropertyId());
		}
	}


	@Override
	public int importHierarchicalStructure(Map map,Long targetConfigGroupId, Long targetParentId) {
		for (Object key: map.keySet()) {
			Object value = map.get(key);
			int maxOrderNum = maxOrderNum(targetConfigGroupId, targetParentId);
			maxOrderNum+=10;
			GroupProperty groupProperty = new GroupProperty();
			groupProperty.setConfigGroupId(targetConfigGroupId);
			groupProperty.setParentId(targetParentId);
			groupProperty.setPropKey(key.toString());

			List<Remark> remarks = remarkService.completeRemark(groupPropertyToCompleteRemark(groupProperty));
			Optional<Remark> first = remarks.stream().findFirst();
			if(first.isPresent()){
				Remark remark = first.get();
				groupProperty.setDescription(remark.getDescription());
				groupProperty.setRemark(remark.getRemark());
			}else{
				groupProperty.setDescription(key.toString());
			}
			groupProperty.setOrderNum(maxOrderNum);
			if(value instanceof Map){
				insertGroupProperty(groupProperty);
				importHierarchicalStructure((Map) value,targetConfigGroupId,groupProperty.getConfigGroupPropertyId());
			}else{
				groupProperty.setPropValue(value.toString());
				insertGroupProperty(groupProperty);
			}
		}
		return 1;
	}

	@Override
	public int addCompleteRemark(GroupProperty groupProperty) {
		Remark remark = groupPropertyToCompleteRemark(groupProperty);
		int i = remarkService.addCompleteRemark(remark);
		return i;
	}

	Remark groupPropertyToCompleteRemark(GroupProperty groupProperty){

		Remark remark = new Remark();
		remark.setDictionary(groupProperty.getPropKey());
		remark.setGroupName("groupProperty");
		remark.setDescription(groupProperty.getDescription());
		remark.setRemark(groupProperty.getRemark());

		HashMap<String, Object> map = Maps.newHashMap();
		map.put("propConstraint",groupProperty.getPropConstraint());
		if(groupProperty.getConfigGroupId()!=null){
			Group group = groupMapper.selectGroupById(groupProperty.getConfigGroupId());
			map.put("propertyPrefix",group.getPropertyPrefix());
		}
		remark.setJson(JSONObject.toJSONString(map));

		return remark;
	}
}
